package com.banciyuan.bcywebview.utils.baidussp;

import android.content.Context;

import com.banciyuan.bcywebview.utils.file.ImageManager;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.nio.charset.Charset;

import okio.BufferedSink;
import okio.BufferedSource;
import okio.Okio;

/**
 * Created by squall1989 on 2017/2/20.
 */

public class SSPCache {


    public static String read(Context mContext, String key) {
        String result = "";
        try {
            File file = new File(ImageManager.getImageFile(mContext) + key);
            if (file.exists()) {
                BufferedSource bufferedSource = Okio.buffer(Okio.source(file));
                result = new String(bufferedSource.readByteArray(), Charset.defaultCharset());
            } else {
                return result;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    public static boolean write(Context mContext, String key, String json) {
        long result = 0;
        try {
            InputStream is = new ByteArrayInputStream(json.getBytes(Charset.defaultCharset()));
            BufferedSource bufferedSource = Okio.buffer(Okio.source(is));
            File dic = new File(ImageManager.getImageFile(mContext));
            File file = new File(ImageManager.getImageFile(mContext) + key);
            if (!dic.exists()) {
                dic.mkdirs();
            }
            if (!file.exists()) {
                file.createNewFile();
            }
            BufferedSink bufferedSink = Okio.buffer(Okio.sink(file));
            result = bufferedSink.writeAll(bufferedSource);
            bufferedSink.close();
            bufferedSource.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result != 0;
    }
}
